package org.advanced.nio;

import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;

/**
 * @author John.zhang
 * @version Id: ZeroCopyClient, v 1.0 2020/12/17 14:49 ZhiYong Exp $
 */
public class ZeroCopyClient {

    public static void main(String[] args) {
        try {
            SocketChannel socketChannel = SocketChannel.open();
            socketChannel.connect(new InetSocketAddress("localhost", 8080));

            FileChannel fileChannel = new FileInputStream("C:/data/io/io.txt").getChannel();
            //把文件发送到通道上面去(避免了通过缓冲区来写)
            //内存缓存区一次性传出最大为8MB
            int position = 0;
            long size = fileChannel.size();
            while (size>0){
                //transferTo这个是核心零拷贝
                long l = fileChannel.transferTo(position, size, socketChannel);
                if(l>0){
                    position+=l;
                    size-=l;
                }
            }
            System.out.println("总数据传输字节数：" + position);
            socketChannel.close();
            fileChannel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
